package org.example.utils;

import lombok.extern.slf4j.Slf4j;
import org.example.bean.dto.FieldDto;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
public class CommonUtil {

    public static Map<String, FieldDto> getFieldMap(Object object) {
        Map<String, FieldDto> map = new HashMap<>();
        if (object == null) return map;
        Field[] fields = object.getClass().getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            FieldDto dto = new FieldDto();
            dto.setFieldName(field.getName());
            try {
                dto.setValue(field.get(object));
            } catch (Exception e) {
                log.error("获取属性值失败，属性名：{}，异常信息：{}", field.getName(), e.getMessage());
            }
            map.put(field.getName(), dto);
        }
        return map;
    }

    public static List<FieldDto> getFieldList(Object object) {
        List<FieldDto> list = new ArrayList<>();
        Field[] fields = object.getClass().getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            FieldDto dto = new FieldDto();
            dto.setFieldName(field.getName());
            try {
                dto.setValue(field.get(object));
            } catch (Exception e) {
                log.error("获取属性值失败，属性名：{}，异常信息：{}", field.getName(), e.getMessage());
            }
            list.add(dto);
        }
        return list;
    }
}
